/**
 * Created by xuelei.kong on 2017/7/16.
 */
var forEach = function (arr, fn) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        var tmp = arr[i];
        if (fn.call(tmp, i, tmp) == false) {
            break;
        }
    }

};

function formatDate(date, fmt) {
    var D = new Date(date);
    var o = {
        "M+": D.getMonth() + 1, //月份
        "d+": D.getDate(), //日
        "h+": D.getHours(), //小时
        "m+": D.getMinutes(), //分
        "s+": D.getSeconds(), //秒
        "q+": Math.floor((D.getMonth() + 3) / 3), //季度
        "S": D.getMilliseconds() //毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (D.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var showDatePicker = function (obj, type) {
    if (type === 1) {
        WdatePicker({
            maxDate: $(obj).parents('.filter-wrapper').find(".to").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    } else {
        WdatePicker({
            minDate: $(obj).parents('.filter-wrapper').find(".from").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    }

};
var colors = ['#ff030c', '#00fff0', '#0aabfa', '#00f735'];

var app = new Vue({
    el: '#app',
    data: function () {
        return {
            loadingFlag: false,
            ztreeLoadingFlag: false,
            startDate: formatDate(new Date().getTime() - 24 * 60 * 60 * 1000, 'yyyy-MM-dd'),
            endDate: formatDate(new Date().getTime(), 'yyyy-MM-dd'),
            equipmentID: [],
            equipment: [],
            zxfx: [
                {
                    name: '正向有功',
                    checked: false,
                    value: 1
                },
                {
                    name: '反向有功',
                    checked: false,
                    value: 2
                },
                {
                    name: '正向无功',
                    checked: false,
                    value: 3
                },
                {
                    name: '反向无功',
                    checked: false,
                    value: 4
                }
            ],
            showTypeList: [
                {
                    name: "天",
                    id: 1
                },
                {
                    name: "月",
                    id: 2
                },
                {
                    name: "年",
                    id: 3
                }
            ],
            showType: 1,
            eleTypeList: [
                {
                    name: "正向有功",
                    id: 10

                },
                {
                    name: "反向有功",
                    id: 20

                },
                {
                    name: "正向无功",
                    id: 30

                },
                {
                    name: "反向无功",
                    id: 40

                }
            ],
            eleType: 10,
            lineOption: {

                title: {
                    text: '',
                    textStyle:{
                        color:'#00fff0'
                    },
                    left:'center',
                    top:'10px'
                }
                ,
                tooltip: {
                    trigger: 'axis',
                    backgroundColor:
                        'rgba(0,0,0,.3)',
                    padding:
                        10,
                    formatter:

                        function (params) {
                            console.log(params);
                            return '<div style="font-size: 12px;"><p style="color:#02fdff">' + params[0].axisValue + '日</p><p style="font-size: 12px;color:#FF47CC">上月：' + params[0].value + '元</p><p style="font-size: 12px;color:#FFCC33">本月：' + params[1].value + '元</p></div>'
                        }
                }
                ,
                backgroundColor: "rgba(0, 0, 0, 0.3)",
                legend:
                    {
                        right: "10%",
                        top: '10',
                        data: [
                            // {
                            //     name: "正向有功电量",
                            //     icon: 'circle',
                            //     textStyle: {
                            //         color: '#00FF00',
                            //         fontSize: 12
                            //     }
                            // }

                        ]
                    }
                ,
                grid: {

                    left: '3%',
                    right:
                        '3%',
                    bottom:
                        '3%',
                    containLabel:
                        true
                }
                ,
                xAxis: {
                    name: "时",
                    type: 'category',
                    boundaryGap: false,
                    axisLine:
                        {
                            lineStyle: {
                                color: '#008078'
                            }
                        }
                    ,
                    axisLabel: {
                        textStyle: {
                            color: '#00f3ff'
                        }
                    }
                    ,
                    data: []
                }
                ,
                yAxis: {
                    name: "单位(KWH)",
                    type:
                        'value',
                    axisLine:
                        {
                            lineStyle: {
                                color: '#008078'
                            }
                        }
                    ,
                    axisLabel: {
                        textStyle: {
                            color: '#00f3ff'
                        }
                    }
                    ,
                    splitLine: {
                        lineStyle: {
                            type: "doote",
                            color:
                                '#4a6b70'

                        }
                    }

                }
                ,
                series: [
                    {
                        name: "正向有功电量",
                        type: 'line',
                        itemStyle: {
                            normal: {
                                color: '#00FF00',
                                lineStyle: {
                                    color: '#00FF00'
                                }
                            }
                        },
                        data: []
                    }
                ]
            },
            barOption: {

                title: {
                    text: '',
                    textStyle:{
                        color:'#00fff0'
                    },
                    left:'center',
                    top:'10px'
                }
                ,
                tooltip: {
                    trigger: 'axis',
                    backgroundColor:
                        'rgba(0,0,0,.3)',
                    padding:
                        10,
                    formatter:

                        function (params) {
                            console.log(params);
                            return '<div style="font-size: 12px;"><p style="color:#02fdff">' + params[0].axisValue + '日</p><p style="font-size: 12px;color:#FF47CC">上月：' + params[0].value + '元</p><p style="font-size: 12px;color:#FFCC33">本月：' + params[1].value + '元</p></div>'
                        }
                }
                ,
                backgroundColor: "rgba(0, 0, 0, 0.3)",
                legend:
                    {
                        right: "10%",
                        top: '10',
                        data: [
                            {
                                name: "正向有功电量",
                                icon: 'circle',
                                textStyle: {
                                    color: '#00FF00',
                                    fontSize: 12
                                }
                            },
                            {
                                name: "反向有功电量",
                                icon: 'circle',
                                textStyle: {
                                    color: '#FFCC33',
                                    fontSize: 12
                                }
                            }

                        ]
                    }
                ,
                grid: {

                    left: '3%',
                    right: '10%',
                    bottom: '3%',
                    containLabel: true
                }
                ,
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                }
                ,
                xAxis: {
                    name: "时",
                    type: 'category',
                    axisLine:
                        {
                            lineStyle: {
                                color: '#008078'
                            }
                        }
                    ,
                    axisLabel: {
                        textStyle: {
                            color: '#00f3ff'
                        }
                    }
                    ,
                    data: [1, 2, 3, 4]
                }
                ,
                yAxis: {
                    name: "单位(KWH)",
                    boundaryGap: [0, 0.01],
                    type:
                        'value',
                    axisLine:
                        {
                            lineStyle: {
                                color: '#008078'
                            }
                        }
                    ,
                    axisLabel: {
                        textStyle: {
                            color: '#00f3ff'
                        }
                    }
                    ,
                    splitLine: {
                        lineStyle: {
                            type: "doote",
                            color:
                                '#4a6b70'

                        }
                    }

                }
                ,
                series: [
                    {
                        name: "正向有功电量",
                        type: 'bar',
                        barWidth: 20,
                        itemStyle: {
                            normal: {
                                color: '#00FF00',
                                lineStyle: {
                                    color: '#00FF00'
                                }
                            }
                        },
                        data: [1, 2, 3, 32]
                    },
                    {
                        name: "反向有功电量",
                        type: 'bar',
                        barWidth:'20',
                        stack: '',
                        itemStyle: {
                            normal: {
                                color: '#FFCC33',
                                lineStyle: {
                                    color: '#FFCC33'
                                }
                            }
                        },
                        data: [3, 22, 3, 23]
                    },
                ]
            },
            list: []
        }
    },
    mounted: function () {


        //ztree

        var that = this;

        // var sbynfxChart = echarts.init(document.getElementById('sbynfx'));
        // sbynfxChart.setOption(that.lineOption);
        //
        // var yngctChart = echarts.init(document.getElementById('yngct'));
        // yngctChart.setOption(that.barOption);

        // this.loadingFlag = true;
        $.ajax({
            url: "http://180.166.106.206:8086/Data/GetTree",
            type: 'GET',
            success: function (res) {
                console.log(res);
                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        py = $("#py").attr("checked") ? "p" : "",
                        sy = $("#sy").attr("checked") ? "s" : "",
                        pn = $("#pn").attr("checked") ? "p" : "",
                        sn = $("#sn").attr("checked") ? "s" : "",
                        // type = {"Y": py + sy, "N": pn + sn};
                        type = {"Y": "", "N": ""};

                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                var setting = {
                    check: {
                        enable: true
                    },

                    data: {
                        simpleData: {
                            enable: true
                        }
                    },

                    view: {
                        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
                    },

                    callback: {
                        onCheck: onCheck
                    }
                };
                that.ztree = $.fn.zTree.init($("#treeDemo"), setting, res.zNodes);
                that.ztreeLoadingFlag = false;
                console.log(res.zNodes[0]);
                var node = that.ztree.getNodeByParam("id", res.zNodes[0].id);
                that.ztree.checkNode(node);
                that.equipmentID.push(res.zNodes[0].id);
                that.equipment.push(res.zNodes[0].name);
                // that.lineOption.series[0].name = that.equipment[0];
                // that.lineOption.legend.data[0].name = that.equipment[0];

                that.lineOption.title.text = that.equipment[0];


                that.getData();

                // 设置高亮字体
                function setHighlight(treeId, treeNode) {
                    console.log(treeNode);
                    return (treeNode.highlight) ? {
                        color: "#EB6100"
                        // "font-weight": "bold",
                        // "background-color": "#EB6100"
                    } : {color: "#01fcf0", "font-weight": "normal"};
                }


                // var node = zTree.getNodeByParam("id",5001);
                // zTree.selectNode(node);

                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);

                function onCheck(e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    var nodes = treeObj.getCheckedNodes(true);
                    console.log(nodes);
                    var v = "";
                    that.equipment = [];
                    that.equipmentID = [];
                    for (var i = 0; i < nodes.length; i++) {
                        v += nodes[i].name + ",";
                        if (!nodes[i].children) {

                        }
                        if (nodes[i].id !== treeNode.id) {
                            treeObj.checkNode(nodes[i], false);
                        } else {
                            that.equipmentID.push(nodes[i].id);
                            that.equipment.push(nodes[i].name);

                            that.lineOption.series[0].name = that.equipment[0];
                            that.lineOption.legend.data[0].name = that.equipment[0];
                        }


                    }


                }


            }

        });


    },
    methods: {
        selectZxfx: function (index) {
            this.zxfx[index].checked = !this.zxfx[index].checked
        },
        selectType: function (type, id) {
            this[type] = id
        },
        //获取折线图数据
        getData: function () {
            var that = this;
            that.loadingFlag = true;

            $.ajax({
                //http://180.166.106.206:8086/EnergyPage/EnergyReportPage?Id=0&begin=2017-03-01&end=2017-03-02&showType=1&Type=1&type2=0
                // url: "http://180.166.106.206:8086/EnergyPage/EnergyReportPage?id=" + that.equipmentID[0] + "&begin=" + that.startDate + "&end=" + that.endDate + "&showType=" + that.showType + "&Type=4&type2=0",
                url: "http://180.166.106.206:8086/EnergyPage/EnergyReportPage?Id=0&begin=2017-03-01&end=2017-03-02&showType=1&Type=1&type2=0",
                dataType: 'json',
                type: "POST",
                success: function (res) {
                    console.log(res);
                    var pieData;
                    that.loadingFlag = false;
                    that.list = res.TrendData;

                    that.lineOption.xAxis.data = [];
                    that.lineOption.series[0].data = [];


                    that.lineOption.xAxis.data=res.TrendLine.Values.Labels;
                    that.lineOption.series[0].data=res.TrendLine.Values.Values;

                    var sbynfxChart = echarts.init(document.getElementById('sbynfx'));
                    sbynfxChart.setOption(that.lineOption);





                }
            });
        },
        //查询方法
        search: function () {

            if (!this.startDate || !this.endDate) {
                alert("请选择起止时间");
                return;
            }
            if (!this.equipmentID.length) {
                alert('请选择设备');
                return;
            }
            this.getData();

        },
        searchNode: function () {
            var value = this.$refs.ztreesearch.value;
            if (value == "") return;

            // 获取搜索的节点
            var nodes = this.ztree.getNodesByParamFuzzy("name", value);
            // 关闭所有节点的高亮
            var allNodes = this.ztree.transformToArray(this.ztree.getNodes());
            for (var i = 0; i < allNodes.length; i++) {
                allNodes[i].highlight = false;
                this.ztree.updateNode(allNodes[i]);
            }
            // 展开第一层节点
            this.ztree.expandAll(false);
            this.ztree.expandNode(this.ztree.getNodes()[0], true);
            // 高亮并展开搜索到的节点
            for (var i = 0; i < nodes.length; i++) {
                nodes[i].highlight = true;
                this.ztree.updateNode(nodes[i]); // 更新节点，让高亮生效
                this.ztree.expandNode(nodes[i].getParentNode(), true);
            }
        },
        searchNodeLazy: function () {
            var timeoutId = null;
            var that = this;
            var value = event.target.value;
            if (timeoutId) {
                console.log(222);
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function () {
                console.log(111);
                that.searchNode(value);
            }, 500);
        },
        setViewModel: function (which) {
            this[which] = event.target.value;
        }

    }
});


$('.extend').hover(function () {
    $('body').toggleClass('extended');

});